from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Comment
from info.utils.commons import login_user_data, login_required
from info.utils.response_code import RET
from . import news_blu


# 新闻点赞功能
@news_blu.route('/comment/like', methods=['POST'])
@login_required
def news_comment_like():
    user = g.user
    # 1接受参数(comment_id,action并进行参数校验)
    # 校验参数完整性
    # 2.根据comment_id查询新闻的信息(如果查不到说明评论信息不存在不存在)
    # 3.根据action进行操作
    # 4.返回点赞成功/取消点赞
    req_dict = request.json
    if not req_dict:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    comment_id = req_dict.get('comment_id')
    action = req_dict.get('action')

    # 校验参数完整性
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    if action not in ('do', 'undo'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 2.根据news_id获取新闻的信息(如果查不到说明新闻不存在)
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询评论信息失败')
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')

    # 3.根据action进行操作
    # 如果点赞
    if action == 'do':
        if comment not in user.like_comments:
            user.like_comments.append(comment)
            comment.like_count += 1
    # 如果action=='undo' 执行取消点赞
    else:
        if comment in user.like_comments:
            user.like_comments.remove(comment)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='操作失败')

    # 4.点赞或取消收藏成功
    return jsonify(errno=RET.OK, errmsg='点赞成功')


# 新闻评论功能
@news_blu.route('/comment', methods=['POST'])
@login_required
def news_comment():
    # 1接受参数(news_id,content,parent_id并进行参数校验)
    req_dict = request.json
    if not req_dict:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    news_id = req_dict.get('news_id')
    content = req_dict.get('content')
    parent_id = req_dict.get('parent_id')
    # 校验参数完整性
    if not all([news_id, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 2.根据news_id获取新闻的信息(如果查不到说明新闻不存在)
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻信息失败')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')
    # 3.创建Comment对象并保存'评论'信息
    comment = Comment()
    comment.user_id = g.user.id
    # comment.uesr_id = g.user.id
    comment.news_id = news_id
    # comment.news_id = news_id
    comment.content = content
    # comment.content = content
    if parent_id:
        comment.parent_id = parent_id
    # if parent_id:
    #     comment.parent_id = parent_id
    # 新闻评论数量+1
    news.comments_count += 1
    # 4.将评论信息添加到数据库中
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存评论信息失败')
    # 5.返回应答,评论新闻或回复评论成功
    return jsonify(errno=RET.OK, errmsg='OK', comment=comment.to_dict())


# 新闻收藏功能
@news_blu.route('/collect', methods=['POST'])
@login_required
def news_collect():
    user = g.user

    # 1.接受参数并校验,新闻id还有动作
    req_dict = request.json
    if not req_dict:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    news_id = req_dict.get('news_id')
    action = req_dict.get('action')
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    if action not in ('do', 'undo'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 2.根据news_id获取新闻信息,如果查不到说明新闻不存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻信息失败')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='新闻不存在')
    # 3.根据action进行操作
    # 如果action=='do' 执行收藏
    if action == 'do':
        if news not in user.collection_news:
            user.collection_news.append(news)
    # 如果action=='undo' 执行取消收藏
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='操作失败')

    # 4.收藏或取消收藏成功
    return jsonify(errno=RET.OK, errmsg='收藏成功')


# 新闻页面显示
@news_blu.route('/<int:news_id>')
@login_user_data
def get_news_detail(news_id):
    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #         # 用户照片信息七牛云
    #         user.avatar_url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not news:
        abort(404)
    try:
        news.clicks += 1
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
    # 从数据库中点击获取新闻点击排行
    rank_news_li = []
    try:
        rank_news_li = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    # 因为前面已经判断了用户是否登陆,
    # 这里只需判断用户是否收藏
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

    # 获取当前新闻评论信息
    comments_li = []
    try:
        # comments_li = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
        comments_li = Comment.query.filter(Comment.news_id == news.id).order_by(Comment.create_time.desc()).all()
        # comments_li = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    # 如果用户未登录,应获取不到like_comments点赞列表
    # 所以like_comments默认为空
    # 再判断用户是否登陆
    # 查看登陆用户是否已经点赞过这条评论,
    # 因此先取出用户点赞的所有资料,
    # 传给前端,前段遍历每条评论时判定,
    # 这条评论是否已经存在与用户点赞的表格中,
    # 如果在的话在将页面此条评论中的赞高亮

    like_comments = []
    if user:
        like_comments = user.like_comments

    return render_template('news/detail.html',
                           user=user,
                           news=news,
                           rank_news_li=rank_news_li,
                           is_collected=is_collected,
                           comments_li=comments_li,
                           like_comments=like_comments,
                           qiniu_domain=constants.QINIU_DOMIN_PREFIX)
